import classNames from 'classnames'
import styles from './chat.module.scss'
import { Flex, Spin } from 'antd'
// , useRef
import React, { useState, useEffect, useRef } from 'react'
import { getHistoryToBackstage, getSessionList, updateHistoryList, add, del } from '@/api/chat-ai'
import { chatSocket } from '@/utils/config'
import ReactMarkdown from 'react-markdown'
import { useSelector } from 'react-redux'

import deletePath from '@/assets/img/delete.png'
import aiPath from '@/assets/img/aiChat.png'

// 定义 Chat 组件的 props 类型
interface ChatProps {
  onClose: (msg: boolean) => void // onClose 是一个无参数无返回值的函数
}

const Chat: React.FC<ChatProps> = ({ onClose }) => {
  /**
   * 变量
   */
  interface historyType {
    historyList: [{ role: string; content: string }]
    id: string | number
    sessionId: string | number
    userId: string | number
  }
  interface currentListType {
    role: string
    content: string | null
  }

  const [sessionList, setSessionList] = useState<historyType[]>([])
  const [currentList, setCurrentList] = useState<currentListType[]>([])
  const [question, setQuestion] = useState('')
  const [isCanSend, setIsCanSend] = useState(true)
  const [currentIndex, setCurrentIndex] = useState(0)
  // let socket: WebSocket
  const [socketInstance, setSocketInstance] = useState<WebSocket>()
  const answer = useRef<HTMLParagraphElement>(null)
  // const ans = useRef(null)
  const { userInfo } = useSelector((state: RootState) => state.handleUser)
  const [spinning, setSpinning] = React.useState<boolean>(false)
  const [LodingText, setLodingText] = useState('数据加载中')
  /**
   *
   */
  useEffect(() => {
    fetchSessionList()

    return () => {
      // 组件销毁时关闭 WebSocket 连接
      socketInstance?.close()
      // socketInstance?.close()
      // closeChat()
    }
  }, [])
  useEffect(() => {}, [currentList])

  /**
   * 函数
   */
  // 建立socket
  const createSocket = (id: number | string) => {
    return new Promise<WebSocket>((resolve, reject) => {
      const socket = new WebSocket(chatSocket + `/websocket/${userInfo.name}/` + id)

      socket.addEventListener('open', () => {
        console.log('连接已打开')
        resolve(socket)
      })

      socket.addEventListener('error', event => {
        console.error('WebSocket连接发生错误:', event)
        reject(event)
      })
    })
  }
  // 关闭
  const closeChat = async () => {
    try {
      setSpinning(true)
      setLodingText('正在关闭，保存会话中，请稍等')
      await updateHistoryList(currentList, sessionList[currentIndex].id)
    } catch (error) {
      console.log(error)
    } finally {
      onClose(false)
      socketInstance?.addEventListener('close', () => {
        console.log('WebSocket连接已关闭')
      })
      socketInstance?.close()
      setSpinning(false)
    }
  }
  // 获取会话列表
  const fetchSessionList = async () => {
    setSpinning(true)
    // userInfo.id
    const res = await getSessionList({ userId: 1 })
    setSpinning(false)
    // await getHistoryToBackstage(sessionList[0].id)
    setSessionList(res.data)
    setCurrentList(res.data[0].historyList)
    setSocketInstance(await createSocket(res.data[0].id))
    getHistoryToBackstage(res.data[0].id)
  }

  // 发送消息
  const sendQuestion = async () => {
    if (!isCanSend || question === '') return
    // const isInser = await insertQuestion()
    // 将当前列表的副本保存到变量中
    const historyList = [...currentList]

    // 添加用户发送的问题和一个空白的助手回复到列表中
    historyList.push({ role: 'user', content: question })
    historyList.push({ role: 'assistant', content: '' })
    // const length = historyList.length
    // 更新当前列表
    setCurrentList(historyList)
    // 设置发送状态为不可用
    setIsCanSend(false)

    // 发送问题到后端
    socketInstance?.send(question)

    const handleMessage = (event: MessageEvent<string>) => {
      if (event.data.includes('{"status":2,')) {
        setIsCanSend(true)
        const j = JSON.parse(event.data)
        const end_t = j.content
        if (answer.current) {
          const updateHistoryList = [...historyList]
          updateHistoryList[updateHistoryList.length - 1].content = answer.current.textContent + end_t
          setCurrentList(updateHistoryList)
          // answer.current.textContent = ''
          // 在需要移除监听器的地方
          socketInstance?.removeEventListener('message', handleMessage)
        }
      } else {
        if (answer.current) {
          // console.log(temp)
          // temp += event.data
          answer.current.textContent += event.data
          // answer.current.innerHTML += event.data
        }
      }
    }

    socketInstance?.addEventListener('message', handleMessage)

    // 清空问题输入框
    setQuestion('')
  }
  //选择会话
  const selectSession = async (index: number) => {
    // 张样子就写就是上一次的index
    const str = JSON.stringify(currentList)
    await updateHistoryList(str, sessionList[currentIndex].id)
    setCurrentIndex(index)

    setCurrentList(sessionList[index].historyList)
    await getHistoryToBackstage(sessionList[index].id)
  }
  //
  const handleKeyDown = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    sendQuestion()
  }
  //
  const addSession = async () => {
    // 用户id
    await add(userInfo.id)
    fetchSessionList()
  }
  //
  const deleteSession = async () => {
    await del(sessionList[currentIndex].id)
    fetchSessionList()
  }

  return (
    <>
      <Spin spinning={spinning} fullscreen tip={LodingText} />
      <div className={classNames(styles.box_chat)} onClick={closeChat}>
        <div className={classNames(styles.chat)} onClick={e => e.stopPropagation()}>
          <Flex style={{ height: '100%' }}>
            <div className={classNames(styles.session_list)}>
              <div className={classNames(styles.header)} onClick={addSession}>
                {/* <div ref={answer}></div> */}
                新建聊天+
              </div>
              {sessionList &&
                sessionList.map((item, index) => (
                  <div
                    className={classNames(styles.list_item, { [styles.selected_list_item]: currentIndex === index })}
                    key={index}
                    onClick={() => selectSession(index)}
                  >
                    {item.historyList[0] && <p>{item.historyList[0].content}</p>}
                    {!item.historyList[0] && <p>新建聊天</p>}
                    <img src={deletePath} alt="" onClick={deleteSession} />
                  </div>
                ))}
            </div>
            <div className={classNames(styles.char_body)}>
              {/* <div ref={ans}>{answer}</div> */}

              <div className={classNames(styles.box_content)}>
                {currentList.map((itme, index) => (
                  <div key={index}>
                    {itme.role === 'assistant' && (
                      <div className={classNames(styles.ai)}>
                        <Flex align="center">
                          <img src={aiPath} alt="" />
                          <div className={classNames(styles.content)}>
                            <ReactMarkdown>{itme.content}</ReactMarkdown>
                          </div>
                          {/* {itme.content} */}
                          {!itme.content && <div ref={answer} className={classNames(styles.content)}></div>}
                        </Flex>
                      </div>
                    )}
                    {/*  */}
                    {itme.role === 'user' && (
                      <div className={classNames(styles.you)}>
                        <Flex align="center">
                          <div className={classNames(styles.content)}>{itme.content}</div>
                          <img src={userInfo.avatar} alt="" />
                        </Flex>
                      </div>
                    )}
                  </div>
                ))}
              </div>
              <form onSubmit={e => handleKeyDown(e)}>
                <div className={classNames(styles.box_send)}>
                  <Flex align="center" style={{ height: '100%', width: '100%' }}>
                    <div className={classNames(styles.input)}>
                      <input onClick={e => e.stopPropagation} type="text" value={question} onChange={e => setQuestion(e.target.value)} />
                    </div>
                    <div className={classNames(styles.btn, { [styles.can_not_send]: !isCanSend })} onClick={sendQuestion}>
                      发送
                    </div>
                  </Flex>
                </div>
              </form>
            </div>
          </Flex>
        </div>
      </div>
    </>
  )
}

export default Chat
